import React, { Component } from 'react'
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { eventBus } from './utils/eventBus';
// 筛选权限的函数
import { filterMenu } from './utils/global';
import Login from './pages/Login';
import Nav from './pages/nav';
const Home=React.lazy(()=>import('./pages/Home'))
const AddAccount=React.lazy(()=>import('./pages/accounts/AddAccount'))
const AccountsList=React.lazy(()=>import('./pages/accounts/AccountsList'))
const AddShop=React.lazy(()=>import('./pages/shop/AddShop'))
const ShopList=React.lazy(()=>import('./pages/shop/ShopList'))
const NotFound=React.lazy(()=>import('./pages/NotFound'))
const Mine=React.lazy(()=>import('./pages/Mine')) 
// 用来动态渲染的数组
const routes = [
  { path: "home", element: Home, roles: ["超级管理员"] },
  { path: "shopList", element: ShopList },
  { path: "addShop", element: AddShop, roles: ["超级管理员"] },
  { path: "accountsList", element: AccountsList },
  { path: "addAccount", element: AddAccount, roles: ["超级管理员"] },
  { path: "mine", element: Mine },
  { path: "*", element: NotFound },
]
export default class App extends Component {
  // 一个类似于mounted的函数
  componentDidMount(){
      eventBus.addListener('refreshRoutes',()=>{
        // 强制当前组件更新
        this.forceUpdate()
      })
  }
  // 渲染的函数
  renderRoutes=()=>{
     const userInfo=localStorage.userInfo
     let arr=[]
     if(!userInfo){//本地未储存
       arr=routes
     }else{
      arr=filterMenu(routes,JSON.parse(userInfo).role)
     }

     console.log('筛选后权限',arr);

     return arr.map(item=>{
      const {element:Comp}=item
      return <Route key={item.path} path={item.path} element={<Comp></Comp>}></Route>
     })
  }
  render() {
    return (
      <React.Suspense fallback={<div>加载中</div>}>
        <BrowserRouter>
          <Routes>
            <Route path='/' element={<Navigate to='/login'></Navigate>}></Route>
            <Route path='/login' element={<Login></Login>}></Route>
            <Route path='/nav' element={<Nav></Nav>}>
            {this.renderRoutes()}
              {/* <Route path='home' element={<Home></Home>}></Route>
              <Route path="shopList" element={<ShopList />} />
              <Route path="addShop" element={<AddShop />} />
              <Route path="accountsList" element={<AccountsList />} />
              <Route path="addAccount" element={<AddAccount />} />
              <Route path='mine' element={<Mine></Mine>}></Route> */}
            </Route>
            <Route path='*' element={<NotFound></NotFound>}></Route>
          </Routes>
        </BrowserRouter>
      </React.Suspense>
    )
  }
}

